package com.gzwanchuang.lszg.module.main;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.gzwanchuang.lszg.R;
import com.gzwanchuang.lszg.adapter.GallerySnapHelper;
import com.gzwanchuang.lszg.adapter.SnapHelperAdapter;
import com.gzwanchuang.lszg.base.BaseFragment;
import com.gzwanchuang.lszg.module.account.AccountActivity;
import com.gzwanchuang.lszg.module.allow.AllowApplyActivity;
import com.gzwanchuang.lszg.module.machines.MachinesActivity;
import com.gzwanchuang.lszg.module.partner.PartnerActivity;
import com.gzwanchuang.lszg.module.policy.PolicyActivity;
import com.gzwanchuang.lszg.module.shop.ShopActivity;
import com.gzwanchuang.lszg.net.Apis;
import com.gzwanchuang.lszg.net.NetworkManager;
import com.gzwanchuang.lszg.net.WebApis;
import com.gzwanchuang.lszg.net.interfaces.OnRequestCallBack;
import com.gzwanchuang.lszg.proto.Index;
import com.gzwanchuang.lszg.proto.MemberOuterClass;
import com.gzwanchuang.lszg.proto.Recharge;
import com.gzwanchuang.lszg.utils.StatusBarUtil;
import com.gzwanchuang.lszg.view.BannerImageHoderView;
import com.gzwanchuang.lszg.view.MyScrollview;
import com.gzwanchuang.lszg.web.ui.WebViewActivity;
import com.google.protobuf.InvalidProtocolBufferException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/2/2 0002.
 */

public class HomeFragment extends BaseFragment {

    private Unbinder unbinder;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.tv_huabo)
    TextView tvHuabo;
    @BindView(R.id.tv_fenpei)
    TextView tvFenpei;
    @BindView(R.id.tv_dai_kan)
    TextView tvDaiKan;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.scrollview)
    MyScrollview scrollview;
    @BindView(R.id.v_top)
    View vTop;
    @BindView(R.id.rv_title)
    LinearLayout rvTitle;
    @BindView(R.id.home_convenient_banner)
    ConvenientBanner convenientBanner;

    private int height = 300;  // 滑动到什么地方完全变色
    private List<Index.get_show_list.List> advDatas;
    private GallerySnapHelper mGallerySnapHelper;
    private SnapHelperAdapter snapAdapter;
    private ArrayList<Recharge.today_earnings.Earningsinfo.List> mData = new ArrayList<>();


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initView() {
        initTitle();
        initEarnView();
    }

    private void initEarnView() {
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        snapAdapter = new SnapHelperAdapter(mContext, mData);
        recyclerview.setAdapter(snapAdapter);
        mGallerySnapHelper = new GallerySnapHelper();
        mGallerySnapHelper.attachToRecyclerView(recyclerview);

    }

    private void loadEarn() {
        NetworkManager.INSTANCE.post(Apis.today_earnings, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Recharge.today_earnings datas = Recharge.today_earnings.parseFrom(bytes);
                mData.clear();
                mData.addAll(datas.getEarningsInfo().getListList());
                snapAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
            }
        });
    }

    private void initTitle() {
        setViewHeight();
        rvTitle.getBackground().setAlpha(0);
        vTop.getBackground().setAlpha(0);
        scrollview.setOnScrollChanged((scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (scrollY <= 0) {  //在顶部时完全透明
                rvTitle.getBackground().setAlpha(0);
                vTop.getBackground().setAlpha(0);
            } else if (scrollY <= height) {  //在滑动高度中时，设置透明度百分比（当前高度/总高度）
                double d = (double) scrollY / height;
                int alpha = (int) (d * 255);
                rvTitle.getBackground().setAlpha(alpha);
                vTop.getBackground().setAlpha(alpha);
            } else { //滑出总高度 完全不透明
                rvTitle.getBackground().setAlpha(255);
                vTop.getBackground().setAlpha(255);
            }
        });


    }

    /**
     * 加载数据项
     */
    private void initBottomBanner() {
        // 加载banner的数据
        NetworkManager.INSTANCE.post(Apis.get_banner, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Index.get_show_list data = Index.get_show_list.parseFrom(bytes);
                advDatas = data.getAdvListList();
                convenientBanner.setPages(new CBViewHolderCreator() {
                    @Override
                    public BannerImageHoderView createHolder(View itemView) {
                        return new BannerImageHoderView(itemView, mContext);
                    }

                    @Override
                    public int getLayoutId() {
                        return R.layout.item_localimage;
                    }
                }, advDatas);
                convenientBanner.startTurning(6000);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });


    }

    /**
     * 加载未读数据
     */
    private void initMessage() {
        NetworkManager.INSTANCE.post(Apis.get_unread_info, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Index.get_unread_info datas = Index.get_unread_info.parseFrom(bytes);
                tvHuabo.setText(datas.getTransfer());
                tvFenpei.setText(datas.getPolicy());
                tvDaiKan.setText(datas.getBill());
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
            }
        });
    }

    private void loadMemberInfo() {
        NetworkManager.INSTANCE.post(Apis.memberDataInfo, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                MemberOuterClass.Member member = MemberOuterClass.Member.parseFrom(bytes);
                if (TextUtils.isEmpty(member.getMemberName())) {
                    tvMemberName.setText(member.getTruename());
                } else {
                    tvMemberName.setText(member.getMemberName());
                }

            }

            @Override
            public void onError(int code, String errorMessage) {

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        initMessage();
        initBottomBanner();
        loadEarn();
        loadMemberInfo();
    }



    @Override
    protected void init() {
    }

    private void setViewHeight() {
        ViewGroup.LayoutParams para1;
        para1 = vTop.getLayoutParams();
        para1.height = StatusBarUtil.getStatusBarHeight(mContext);
        vTop.setLayoutParams(para1);
        vTop.setBackgroundResource(R.drawable.shape_gradient);
    }

    @OnClick({R.id.home_category_one, R.id.home_category_two, R.id.home_category_three, R.id.home_category_four,
            R.id.home_category_five, R.id.ll_allow, R.id.ll_zhen, R.id.ll_dai, R.id.iv_message,R.id.tv_zhen_che})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.home_category_one:
                startActivity(AccountActivity.class);
                break;
            case R.id.home_category_two:
                WebViewActivity.startActivity(mContext, WebApis.shopping);
                break;
            case R.id.home_category_three:
                startActivity(PartnerActivity.class);
                break;
            case R.id.home_category_four:
                startActivity(ShopActivity.class);
                break;
            case R.id.home_category_five:
                startActivity(MachinesActivity.class);
                break;
            case R.id.ll_allow:
                startActivity(AllowApplyActivity.class);
                break;
            case R.id.ll_zhen:
                startActivity(PolicyActivity.class);
                break;
            case R.id.ll_dai:
                WebViewActivity.startActivity(mContext, WebApis.paymentForGoods);
                break;
            case R.id.iv_message:
                startActivity(MessageActivity.class);
                break;
            case R.id.tv_zhen_che:
                WebViewActivity.startActivity(mContext, WebApis.policy);
                break;

        }
    }
}
